package com.itboye.mengwu.app.ui.aiwujia;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.location.Poi;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.SoftwareUtil;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.ui.aiwujia.ActivityAiwujiaMomPublish.GridAdapter;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.testpic.ui.Bimp;
import com.itboye.mengwu.testpic.ui.FileUtils;
import com.itboye.mengwu.testpic.ui.PhotoActivity;
import com.itboye.mengwu.widget.FixGridLayout;
import com.itboye.mengwu.widget.MyGridView;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;

public class ActivityBaoBaoLePublish extends BaseActivity implements Observer,
		OnClickListener {

	private MyGridView aiWuJiaGridView;
	private GridAdapter adapter;
	// private TextView activity_selectimg_send;
	// private ImageView imgPublishBack;
	// 标题
	private EditText edttitle;
	// 内容
	private EditText edtcontext;
	private String title;
	private String contextEd;
	TextView txt_save;
	TieZiPresenter tanPresenter;
	public final static int HU = 0;
	TextView place;

	boolean ischeck = false;
	FixGridLayout biaoqian;
	ImageView back;
	TextView txt_title;
	TextView txt_cancel;
	Button btn_ok;
	RelativeLayout fenlei;
	TextView baoyou, daofu;
	LocationManager locationManager = null;
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_publish_mom;
	}

	@Override
	public void onMyCreate() {
		tanPresenter = new TieZiPresenter(this);
		txt_title.setText("发布内容");
		txt_cancel.setText("发布");
		place = (TextView) findViewById(R.id.place);
		fenlei.setVisibility(View.GONE);
		btn_ok.setVisibility(View.GONE);
		Init();
		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
		mLocationClient.registerLocationListener(myListener);
		initLocation();

	}

	private StringBuffer attachments;
	protected ArrayList<String> uploadedUrl = new ArrayList<String>();
	public static  ArrayList<String> imgUrls = new ArrayList<>();

	public void Init() {
		aiWuJiaGridView = (MyGridView) findViewById(R.id.aiWuJiaGridView);
		aiWuJiaGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		
		aiWuJiaGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == imgUrls.size()) {
					SoftwareUtil.showOrHideSoftware(arg1, MainApplication.context, false);
					new PopupWindows(ActivityBaoBaoLePublish.this,
							aiWuJiaGridView);
				} else {
					Intent intent = new Intent(ActivityBaoBaoLePublish.this,
							PhotoActivity.class);
					intent.putExtra("imgUrls", imgUrls);
					intent.putExtra("ID", arg2);
					intent.putExtra("type", "baobaole");
					startActivityForResult(intent, 101);//(intent);
					// finish();

				}
			}
		});
	}

	public void onBitMap() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < imgUrls.size(); i++) {
			String Str = imgUrls.get(i).substring(
					imgUrls.get(i).lastIndexOf("/") + 1,
					imgUrls.get(i).lastIndexOf("."));
			list.add(FileUtils.SDPATH + Str + ".JPEG");
		}

		// 高清的压缩图片全部就在 list 路径里面了
		// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
		// 完成上传服务器后 .........

		title = edttitle.getText().toString().trim();
		contextEd = edtcontext.getText().toString().trim();

		if (title == null || title == "") {
			ByAlert.alert("请输入标题");
			return;
		}
		if (contextEd == null || contextEd == "") {
			ByAlert.alert("请输入内容");
			return;
		}
		final TieZiPresenter tanPresenter = new TieZiPresenter(this);
		if (imgUrls.size() > 0) {
			for (int j = 0; j < imgUrls.size(); j++) {
				System.out.println("路径" + imgUrls.get(j));
				ImageCompressAndUpload.getInstance().execute(imgUrls.get(j),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								ByAlert.alert("图片成功");

								if (uploadedUrl.size() == imgUrls.size()) {
									if (uploadedUrl.size() > 0) {

										attachments = new StringBuffer();
										attachments.append(uploadedUrl.get(0));
										for (int i = 1; i < uploadedUrl.size(); i++) {
											attachments.append(",").append(
													uploadedUrl.get(i));
										}

									}
									LuntanTieZiBean bean = new LuntanTieZiBean();
									bean.setUid((String) SPUtils.get(
											ActivityBaoBaoLePublish.this, null,
											SpPublicParams.UID, ""));
									bean.setSubject(title);
									bean.setMessage(contextEd);
									bean.setAuthor((String) SPUtils.get(
											ActivityBaoBaoLePublish.this, null,
											SpPublicParams.NICK_NAME, ""));
									bean.setFid(4 + "");
									bean.setAttachments(attachments);
									tanPresenter.add(bean);
								}

							}

							@Override
							public void OnError(String resultData) {
								ByAlert.alert("发表出错了╰(￣▽￣)╭");
								// toast.show();
							}
						},"bbs");
			}
		} else {
			LuntanTieZiBean bean = new LuntanTieZiBean();
			bean.setUid((String) SPUtils.get(ActivityBaoBaoLePublish.this,
					null, SpPublicParams.UID, ""));
			bean.setSubject(title);
			bean.setMessage(contextEd);
			bean.setAuthor((String) SPUtils.get(ActivityBaoBaoLePublish.this,
					null, SpPublicParams.NICK_NAME, ""));
			bean.setFid(4 + "");
			bean.setAttachments(null);
			tanPresenter.add(bean);
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return (imgUrls.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == imgUrls.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setTag("file://" + imgUrls.get(position));
				XImageLoader.load("file://" + imgUrls.get(position),
						holder.image);
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// Intent intent = new
					// Intent(ActivityAiwujiaMomPublish.this,
					// AiWuJiaTestPicActivity.class);
					// intent.putExtra("hu", HU);
					// startActivityForResult(intent, 1100);
					// dismiss();
					// finish();
					new PhotoSelectFragment(new PhotoSelect(), 9).show(
							getSupportFragmentManager(), null);
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				imgUrls.add(string);

			}
			adapter = new GridAdapter(ActivityBaoBaoLePublish.this);
			aiWuJiaGridView.setAdapter(adapter);
		}

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";
	public String addr;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			 if (imgUrls.size() < 9 && resultCode == -1) {
			 imgUrls.add(path);
			 }
			 adapter = new GridAdapter(this);
				aiWuJiaGridView.setAdapter(adapter);
			break;
		}
		if(requestCode==101&&resultCode==102){
			adapter = new GridAdapter(this);
			aiWuJiaGridView.setAdapter(adapter);
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == TieZiPresenter.AddTieZiSuccess) {
				ByAlert.alert(entity.getData() + "");
				edtcontext.setText("");
				edttitle.setText("");
				finish();
			} else if (entity.getEventType() == TieZiPresenter.AddTieZiSuccess) {
				ByAlert.alert(entity.getData() + "");
			}
		}
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			imgUrls.clear();
			finish();
			break;
		case R.id.edttitle:
			edttitle.setFocusable(true);
			edttitle.setFocusableInTouchMode(true);
			edtcontext.setFocusable(true);
			edtcontext.setFocusableInTouchMode(true);
			break;
		case R.id.txt_cancel:
			showProgressDialog("發佈中，請稍後", true);
			onBitMap();
			break;

		default:
			break;
		}
	}

	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			StringBuffer sb = new StringBuffer(256);

			// sb.append("time : ");
			// sb.append(location.getTime());
			// sb.append("\nerror code : ");
			// sb.append(location.getLocType());
			// sb.append("\nlatitude : ");
			// sb.append(location.getLatitude());
			// sb.append("\nlontitude : ");
			// sb.append(location.getLongitude());
			// sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				addr = location.getAddrStr();
				place.setText(location.getAddrStr());
				Log.d("hu",
						location.getAddrStr() + "getCountry()"
								+ location.getCountry());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr()); // 运营商信息
				addr = location.getAddrStr();
				place.setText(location.getAddrStr());
				sb.append("网络定位成功");
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			Log.d("hu",
					location.getLocationDescribe() + "位置语义化信息"
							+ location.getCountry());
			List<Poi> list = location.getPoiList();// POI数据 if (list != null) {
			sb.append("\npoilist size = : ");
			Log.d("hu", sb.toString() + "sb");
		}
	}

	private void initLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);
		option.setCoorType("bd09ll");// 可选，默认gcj02，设置返回的定位结果坐标系
		int span = 1000;
		option.setScanSpan(span);
		option.setIsNeedAddress(true);// 可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(true);// 可选，默认false,设置是否使用gps
		option.setLocationNotify(true);
		option.setIsNeedLocationDescribe(true);
		option.setIsNeedLocationPoiList(true);
		option.setIgnoreKillProcess(false);
		option.SetIgnoreCacheException(false);
		option.setEnableSimulateGps(false);// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		mLocationClient.setLocOption(option);
		mLocationClient.start();
	}
}
